import React, { useState, useEffect, useRef } from 'react'
import { Table, Dropdown, Button, Input, Space, Modal, Form, message, Tag } from 'antd';
import { DownOutlined, RedoOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom/cjs/react-router-dom.min';
import axios from 'axios';
function DeviceManage(props) {
  const [open, setOpen] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const [nowItem, setNowItem] = useState("");
  const [dataSource, setDataSource] = useState([])
  const [value1, setValue1] = useState("")
  const [value2, setValue2] = useState("")
  const [value3, setValue3] = useState("")
  const [valu14, setValue4] = useState("")
  const [values, setValues] = useState({
    modifier: 'public',
    gatewayname: nowItem?.gatewayname,
    gatewayid: nowItem?.gatewayid,
    mqttpassword: nowItem?.mqttpassword,
    introduce: nowItem?.introduce,
  })

  const { TextArea } = Input;
  const stateList = ["在线", "离线", "中断"]
  const colorList = ["green", "red", "orgen"]
  const useFrom = useRef();

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      fixed: "left",
      width: "5%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '设备名称',
      dataIndex: 'gatewayname',
      key: 'devicename',
      align: "center",
      fixed: "left",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '设备ID',
      dataIndex: 'gatewayid',
      key: 'deviceid',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    // {
    //   title: "下级设备数",
    //   dataIndex: 'lowdevicenum',
    //   key: 'lowdevicenum',
    //   align: "center",
    //   className: "wrapTitle",
    //   render: (text) => {

    //     return <span style={{ fontSize: "12px" }}>{text}</span>
    //   }
    // },
    {
      title: "设备状态",
      dataIndex: 'gatewaystate',
      key: 'devicestate',
      align: "center",
      className: "wrapTitle",
      render: (text) => {
        return <Tag color={colorList[text]}>{stateList[text]}</Tag>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      key: 'createtime',
      align: "center",
      className: "wrapTitle",
      width: "10%",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      align: "center",
      render: (text, item) => {
        return (
          <Space>
            <a style={{ fontSize: "12px", color: "#4e9dfd" }} onClick={() => { setDetail(item) }}>详情</a>
            {/* <a style={{ fontSize: "12px", color: "#4e9dfd" }} >测试连接</a> */}
            <Dropdown
              menu={{
                items: [
                  {
                    key: '1',
                    label: (
                      <a style={{ fontSize: "12px", color: "#4e9dfd" }} onClick={() => { updateDev(item) }}>编辑</a>
                    ),
                  },
                  {
                    key: '2',
                    label: (
                      <a style={{ fontSize: "12px", color: "#4e9dfd" }} onClick={() => { deleteDev(item) }}>删除</a>
                    )
                  }
                ]
              }}
            >
              <a style={{ fontSize: "12px", color: "#4e9dfd" }} onClick={(e) => e.preventDefault()}>
                更多操作
                <DownOutlined />
              </a>
            </Dropdown>
          </Space>)

      }
    }
  ];
  const setDetail = (item) => {
    props.setDetail(item)
    props.history.push("/app/devmanage/detail")
  }
  const deleteDev = (item) => {

    axios.get("/gateway/delete?id=" + item.id).then(res => {
      if (res.data === 1) {
        setDataSource(dataSource.filter(obj => obj.id !== item.id))
        messageApi.open({
          type: 'success',
          content: '删除成功',
        });
      } else {
        messageApi.open({
          type: 'success',
          content: '删除失败',
        });
      }
    })
  }
  const updateDev = (item) => {
    setNowItem(item)
    setOpen(true);
  }
  const insertDev = () => {
    setOpen(true);
  }

  const onCreate = (values) => {
    if (nowItem !== "") {
      axios.post("/gateway/update", {
        id: nowItem.id,
        ...values,
      }).then(res => {
        if (res.data) {
          messageApi.open({
            type: 'success',
            content: '修改成功',
          });
          var nowdata = dataSource
          let targetObject = nowdata.find(obj => obj.id === nowItem.id);
          if (targetObject) {
            targetObject.gatewayname = values.gatewayname;
            targetObject.gatewayid = values.gatewayid;
            targetObject.mqttpassword = values.mqttpassword;
            targetObject.introduce = values.introduce;
          }
          setDataSource(nowdata)
          setNowItem("")
        }
      })
    } else {
      axios.post("/gateway/insert", {
        ...values,
        gatewaystate: "1",
      }).then(res => {
        messageApi.open({
          type: 'success',
          content: '添加成功',
        });
        setDataSource([...dataSource, res.data])
      })

    }
    setOpen(false);

  };
  // var value = ["", "", "", ""]
  // const ran = (index) => {
  //   var r = String(generateRandomNumber())
  //   if (index === 1) {
  //     setValues({
  //       modifier: 'public',
  //       gatewayname: value[0],
  //       gatewayid: r,
  //       mqttpassword: value[2],
  //       introduce: value[3],
  //     })
  //     value[1] = r
  //   } else {
  //     setValues({
  //       modifier: 'public',
  //       gatewayname: value[0],
  //       gatewayid: value[1],
  //       mqttpassword: r,
  //       introduce: value[3],
  //     })
  //     value[2] = r
  //   }

  //   console.log(value);
  // }

  // const setValue = (e, index) => {
  //   value[index] = e.target.value
  // }
  const ran = (e, index) => {
    switch (index) {
      case 1:
        setValue1(e.target.value)
        setValues({
          modifier: 'public',
          gatewayname: e.target.value,
          gatewayid: value2,
          mqttpassword: value3,
          introduce: valu14,
        })
        break
      case 2:
        setValue2(e.target.value)
        setValues({
          modifier: 'public',
          gatewayname: value1,
          gatewayid: e.target.value,
          mqttpassword: value3,
          introduce: valu14,
        })
        break
      case 3:
        setValue3(e.target.value)
        setValues({
          modifier: 'public',
          gatewayname: value1,
          gatewayid: value2,
          mqttpassword: e.target.value,
          introduce: valu14,
        })
        break
      case 4:
        setValue4(e.target.value)
        setValues({
          modifier: 'public',
          gatewayname: value1,
          gatewayid: value2,
          mqttpassword: value3,
          introduce: e.target.value,
        })
        break

    }

  }
  const setRan = (index) => {
    var r = String(generateRandomNumber())
    if (index === 1) {
      setValues({
        modifier: 'public',
        gatewayname: value1,
        gatewayid: r,
        mqttpassword: value3,
        introduce: valu14,
      })
      setValue2(r)
    } else {
      setValues({
        modifier: 'public',
        gatewayname: value1,
        gatewayid: value2,
        mqttpassword: r,
        introduce: valu14,
      })
      setValue3(r)
    }
  }
  const generateRandomNumber = () => {
    return Math.floor(Math.random() * 900000) + 100000;
  }
  const ranId = () => {
    var idList = []
    for (var i = 0; i < dataSource.length; i++) {
      idList[i] = dataSource.gatewayid
    }
    let randomNumber;
    do {
      randomNumber = String(generateRandomNumber())  // 生成一个6位的随机数
    } while (idList.includes(randomNumber));
    return randomNumber
  }

  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal
        open={open}

        title={nowItem !== "" ? "编辑设备" : "添加设备"}
        okText="确定"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          ref={useFrom}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
            gatewayname: nowItem?.gatewayname,
            gatewayid: nowItem === "" ? ranId() : nowItem.gatewayid,
            mqttpassword: nowItem === "" ? String(generateRandomNumber()) : nowItem.mqttpassword,
            introduce: nowItem?.introduce,
          }}
        // initialValues={values}
        >
          <Form.Item
            name="gatewayname"
            label="设备名称"
            rules={[
              {
                required: true,
                message: '未输入设备名称！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="gatewayid"
            label="设备ID"
            rules={[
              {
                required: true,
                message: '未输入设备Id！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="mqttpassword"
            label="MQTT密码"
            rules={[
              {
                required: true,
                message: '未输入MQTT密码！',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="introduce"
            label="设备介绍"
          >
            <TextArea rows={4} />
          </Form.Item>
          {/* <Form.Item
            name="gatewayname"
            label="设备名称"
            rules={[
              {
                required: true,
                message: '未输入设备名称！',
              },
            ]}
          >
            <Input onBlur={(e) => { ran(e, 1) }} />
          </Form.Item> */}
          {/* <Form.Item
            name="gatewayid"
            label={<span>设备ID<RedoOutlined onClick={() => setRan(1)} /></span>}
            rules={[
              {
                required: true,
                message: '未输入设备Id！',
              },
            ]}
          >
            <Input onBlur={(e) => { ran(e, 2) }} />
          </Form.Item>
          <Form.Item
            name="mqttpassword"
            label={<span>MQTT密码<RedoOutlined onClick={() => setRan(2)} /></span>}
            rules={[
              {
                required: true,
                message: '未输入MQTT密码！',
              },
            ]}
          >
            <Input onBlur={(e) => { ran(e, 3) }} />
          </Form.Item>

          <Form.Item
            name="introduce"
            label="设备介绍"
          >
            <TextArea rows={4} onBlur={(e) => { ran(e, 4) }} />
          </Form.Item> */}
        </Form>
      </Modal>
    );
  };
  useEffect(() => {
    axios.get("/gateway/selectall").then(res => {
      setDataSource(res.data)
    })

  }, [])
  return (
    <div>
      {contextHolder}
      <div style={{ textAlign: "right" }}>
        <Button style={{ fontSize: "12px", borderRadius: "4px", margin: "0 0 0 10px" }} onClick={() => { window.location.reload(); }}>刷新</Button>
        <Button style={{ color: "white", fontSize: "12px", borderRadius: "4px", margin: "0 0 0 10px", background: "#4e9dfd" }} onClick={() => { insertDev() }}>新建</Button>
      </div>
      <Table
        columns={columns} dataSource={dataSource} style={{ margin: "5px 0 0 0" }}
        rowKey={(item) => item.id}
        pagination={{}}
        size='small'
        scroll={{ x: 1200 }}
      >
      </Table>
      <CollectionCreateForm
        open={open}
        onCreate={onCreate}

        onCancel={() => {
          setOpen(false);
          setNowItem("")
        }}
      />
    </div >
  )
}
const mapStateToProps = ({ DetailOpen: { row } }) => ({
  row
})
const mapDispatchToProps = {
  setDetail(item) {
    return {
      type: "change_detailOpen",
      row: item
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(DeviceManage))
